#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"

/* find the string between two specified strings from the source string */
char * find_string(char * srcstr, const char * left, const char * right, char * res)
{
	char *lpos, *rpos;
	int rslen;

	res[0] = 0;
	lpos = strstr(srcstr, left);
	if (lpos == 0) return 0;
	lpos += strlen(left);
	rpos = strstr(lpos, right);
	if (rpos == 0) return 0;

	rslen = rpos - lpos;
	memcpy(res, lpos, rslen);
	res[rslen] = 0;

	return rpos + strlen(right);
}

/* replace a word in the string to an another word */
void replace(const char * str, const char * findword, const char * replace, char * buf)
{
	char *prepos, *curpos;
	int findlen = strlen(findword);
	int replacelen = strlen(replace);
	int buflen;
	
	prepos = curpos = (char *)str;
	buflen = 0;
	while (1) {
		curpos = strstr(prepos, findword);
		if (curpos == NULL) break;
		memcpy(buf + buflen, prepos, curpos - prepos);
		buflen += (curpos - prepos);
		memcpy(buf + buflen, replace, replacelen);
		buflen += replacelen;
		prepos = curpos + findlen;
	}

	if (buflen == 0)
		strcpy(buf, str);
	else
		memcpy(buf + buflen, prepos, strlen(prepos)+1);
}

/* filter html tag from the string */
void filter_tag(char * str)
{
        char *ltpos, *rtpos;

        ltpos = rtpos = str;
        while (1) {
                ltpos = strstr(str, "<");
                if (ltpos == NULL) return;
                rtpos = strstr(ltpos, ">");
                if (rtpos == NULL) return;
                strcpy(ltpos, rtpos+1);
        }
}

/* generate the human sensible speed string */
void gen_size_str(char * size_str, double size)
{
	static char *size_units[] = { "B", "K", "M", "G" };
	int sizeunit, i;

	sizeunit = 0;
	for (i=0; i<4; i++) {
		if ((int)(size/1024) > 0) {
			size /= 1024;
			sizeunit++;
		} else {
			break;
		}
	}

	sprintf(size_str, "%.2f %s", size, size_units[sizeunit]);
}

/* generate the human sensible speed string */
void gen_speed_str(char * speed_str, double speed)
{
	static char *speed_units[] = { "B/s", "K/s", "M/s", "G/s" };
	int speedunit, i;

	speedunit = 0;
	for (i=0; i<4; i++) {
		if ((int)(speed/1024) > 0) {
			speed /= 1024;
			speedunit++;
		} else {
			break;
		}
	}

	sprintf(speed_str, "%.2f %s", speed, speed_units[speedunit]);
}
